//
//  FileDownload.m
//  iengage
//
//  Created by Luis Ziliani on 2/12/09.
//  Copyright 2009 Manas. All rights reserved.
//

#import "FileDownload.h"


@implementation FileDownload

@synthesize path;

- (void) dealloc {
	[self setPath: nil];
	[data release];
	[super dealloc];
}

- (void) startDownloadURL:(NSString *) url withUser:(NSString *)usr andPassword:(NSString *) pass file:(NSString*)file delegate:(id<HttpRequestDelegate>) dlg {
	[self setPath: file];
	
	[data release];
	data = [[NSMutableData alloc] init];
	
	[self openURL:url withUser:usr andPassword:pass delegate:dlg];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // this method is called when the server has determined that it	
    // has enough information to create the NSURLResponse
    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
	
	[data setLength:0];
	[super connection:connection didReceiveResponse: response];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dt
{
	[data appendData:dt];
	
	[super connection: connection didReceiveData:dt];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object	
    [super connection:connection didFailWithError:error];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	
	@try {
		[[NSFileManager defaultManager] createFileAtPath:[self path]
												contents:data attributes:nil];

		[delegate requestEndedOk];
	}
	@catch (NSException * e) {
		[delegate informError:[e description]];
	}
	@finally {
		// release the connection, and the data object
		[connection release];
	}
}

@end
